import { useParams, useSearchParams } from "react-router-dom"
import { MyHead } from "../../../components/head";
import { AntOutline, RightOutline , HeartOutline , FillinOutline ,LikeOutline } from 'antd-mobile-icons'
import {Card, Toast, Button , Tag , Image , Avatar  , ImageViewer, Popup , TextArea , Rate , List  } from "antd-mobile";
import {useState,useEffect} from 'react'
import { addCol, addPings, changeCol, changeHot, changeLikes, changePings, clickLikes, delCol, deleteLikes, getPings, getmsbyid, userCol, userLikes } from "../../../api/AddMs";
import dayjs from 'dayjs'
import _, { has } from 'lodash'
import { useSelector } from "react-redux";
import { RootReducer } from "../../../types/store";
import { useTiaoZhuan } from "../../../hooks/routers";
import { useDebounceEffect, useDebounceFn } from "ahooks";
import { base } from "../../../util";
const styles = {
    center:{
        display:"flex",
        alignItems:'center',
        color:"#999"
    },
    flex:{
        display:"flex",
        alignItems:'center',
        justifyContent:'space-between',
        width:'100%',
        fontSize:16
    }
}
const Datail = () => {
    const [query] = useSearchParams();
    const [item,setItem] = useState<addmsType | null>(null)
    const params = useParams();
    const [hasLike,setHasLike] = useState(false)
    const [hasCollect,setHasCollect] = useState(false)
    const [imgList,setImgList] = useState([])
    const [visible,setVisible] = useState(false)
    const [index,setIndex] = useState<number>(0)
    const {Tz} = useTiaoZhuan()
    const [show,setShow] = useState(false)
    const [rate,setRate] = useState(5)
    const [comment,setComment] = useState('')
    const [commentList,setCommentList] = useState<pingsType[]>([])
    const LevelTypes = [
        [
            { label: '简单', value: 1 },
            { label: '复杂', value: 2 },
            { label: '困难', value: 3 },
            { label: '地狱', value: 4 },
            { label: '无解', value: 5 },
        ]
    ]
    const userData = useSelector<RootReducer, foundUserType|null>(s=>s.MyData.userData)
    const addLikeAction = async()=>{
        if(userData?.phone && localStorage.getItem('token')){
            if(hasLike){
                setHasLike(false);
                item!.likes--;
                item!.hot-=2;
                let dats = await userLikes(userData.phone,params.id!)
                console.log(dats.result.find(item=>item.phone == userData.phone)!._id);
                
                let res = await deleteLikes(params.id!,userData.phone)
                
                if(res.code == 200){
                    await changeLikes(params.id!,item!.likes)
                    await changeHot(params.id!,item?.hot!)
                    getDetailData();
                    
                }
            }else{
                setHasLike(true);
                item!.likes++;
                item!.hot+=2;
                let res = await clickLikes(userData?.phone,params.id!,item!);
                let res2 = await userLikes(userData.phone,params.id!)
                if(res.code == 200){
                    await changeLikes(params.id!,item!.likes) 
                    await changeHot(params.id!,item?.hot!)
                    getDetailData()
                    
                }
            }
        }else{
            Tz('/login')
        }

    }
    const addCollectAction = async()=>{
        if(userData?.phone && localStorage.getItem('token')){
            if(hasCollect){
                setHasCollect(false);
                item!.collects--;
                item!.hot -=3;
                let res = await delCol(params.id!,userData.phone)
                if(res.code == 200){
                    await changeCol(params.id!,item!.collects)
                    await changeHot(params.id!,item?.hot!)
                    getDetailData();
                    
                }
            }else{
                setHasCollect(true);
                item!.collects++;
                item!.hot+=3;
                let res = await addCol(userData?.phone,params.id!,item!);
                if(res.code == 200){
                    await changeCol(params.id!,item!.collects)
                    await changeHot(params.id!,item?.hot!)
                    getDetailData()
                    
                }
            }
        }else{
            Tz('/login')
        }
    }
    // const changeHotApi = async(hot:number)=>{
    //     let res = await changeHot(params.id!,hot)
    //     if(res.code == 200){
            
    //     }
    // }
    const addLikeJL = useDebounceFn(addLikeAction,{wait:500})
    const addCollectJL = useDebounceFn(addCollectAction,{wait:500})

    const getDetailData = async ()=>{
        let res = await getmsbyid(
            params.id!
        )
        setItem(res.result)
        if(res.code == 200){
            if(userData?.phone != res.result.author.phone){
                // 不能自己给自己刷热度 
                changeHot(res.result._id, res.result.hot+1) // 每次进来hot+1 
            }
            
            let res2 = await userLikes(userData!.phone,params.id!)
            console.log(res2);
            
            let res3 = await userCol(userData!.phone,params.id!)

            if(res2.result.length != 0){
                setHasLike(true)
            }else{
                setHasLike(false)
            }
            if(res3.result.length != 0){
                setHasCollect(true)
            }else{
                
                setHasCollect(false)
            }
        }
        }
    //获取评论列表
    const getPingsData = async()=>{
        let res = await getPings(params.id!)
        if(res.code == 200){
            setCommentList(res.result)
        }
        
    }
    // 点击评论按钮
    const addPingsone = ()=>{
        if(!localStorage.getItem('token') || !userData?.phone){
            Tz('/login')
        }
        setShow(true)
    }
    // 点击添加评论
    const addToPings = async()=>{
        let res =await addPings(rate,comment,item!,new Date(),params.id!)
        console.log(res);
        if(res.code ==200){
            setComment('');
            setShow(false);
            await changePings(params.id!,(item!.pings?item!.pings:0)+1) // 次数 )
            if(userData!.phone != item!.author.phone){
                await changeHot(params.id!,item!.hot+4) // 每次评论+4
            }
            getDetailData()
            getPingsData()
        }
    }
    useEffect(()=>{
        getDetailData()
        getPingsData()
    },[])
    return (
        <div>
            <MyHead title={query.get('canpany')!}></MyHead>
            <div style={{paddingTop:50}}>

            
                {
                    item && <Card
                    title={
                        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',width:'100%'}}>
                            <span >
                                {item.campany}
                            </span>
                            <div style={styles.center}>
                                <Avatar  style={{borderRadius:'50%','--size':'25px'}} src={item.author.avatar? item.author.avatar?.replace(/public/,"http://101.37.23.156:2219") : ''}></Avatar>
                                <span style={{fontSize:12}} className='ml10'>{item.author.username}</span>
                            </div>
                        </div>
                    }
                    style={{ borderRadius: '16px' , marginTop:10 , border:'1px solid #ddd'}}
                    >
                    <div className='mt10' style={styles.center} >
                        <div>
                        发布时间: <span>{dayjs(item.time).format('YYYY-MM-DD HH:mm') }</span>
                        </div>
                    </div>
                    <div className='mt10' style={styles.center} >
                        <div>
                        面试地址: <span>{item.address}</span>
                        </div>
                    </div>
                    <div className='mt10' style={styles.center} >
                        <div>
                        面试时间: <span>{dayjs(item.date).format('YYYY-MM-DD HH:mm') }</span>
                        </div>
                    </div>
                    <div className='mt10' style={styles.center} >
                        <div>
                        面试难度: 
                        <span>
                            { _.find(LevelTypes[0],(v:any,index)=>v.value==item.level[0])?.label}
                            {/* {
                                LevelTypes[0][item.level[0]].label
                            } */}
                        </span>
                        </div>
                    </div>
                    <div className='mt10' style={styles.center} >
                        <div>
                        当前热度: <span>{ item.hot }</span>
                        </div>
                    </div>
                    <div className=''  >
                        <div className="tag-list" style={{display:'flex',flexWrap:'wrap'}}>
                            {
                                _.map(item.tags , (item,index)=>{

                                    
                                    return (
                                        <Tag className="mt10 mr10 " color={item.check == undefined? '#2db7f5':( item.check?'#2db7f5':'')}  style={{padding:2}}  key={index} >
                                            {item.label}
                                        </Tag>
                                    )
                                })
                            }
                        </div>
                    </div>
                    <div className='imgone mt10 ' style={{marginTop:10,display:'flex',flexWrap:'wrap',}}>

                        {
                            item.imgs.map((v:any,i:any)=>(
                                <Image onClick={()=>{
                                    setVisible(true)
                                    setIndex(i)
                                }} key={i} style={{borderRadius:10,width:"30%",height:100,margin:"10px 10px 0 0",border:'1px solid #f4f4f4'}} src={v?.imgSrc?.replace(/public/,base)} />
                            ))
                        }
                    </div>
                    <div className='imgone mt10 ' style={{marginTop:10}}>
                        {
                            item.audioSrc && <audio className='mt10' src={ item.audioSrc.replace(/public/,base)} controls ></audio>
                        }
                    </div>
                    { <div className="mt10" style={{fontSize:16}} dangerouslySetInnerHTML={{__html:item.content }}>
                        
                    </div>}

                    
                    <div className="mt10">
                        <div style={styles.flex}  > 
                            <div style={{...styles.center,color:hasLike?'#f50':''}} onClick={addLikeJL.run}>
                                <LikeOutline  />
                                <span>{item.likes}</span>
                            </div>
                            <div style={{...styles.center,color:hasCollect?"#f50":''}} onClick={addCollectJL.run}>
                                <HeartOutline />
                                <span>{item.collects}</span>
                            </div>
                            <div style={styles.center} onClick={addPingsone}>
                                <FillinOutline />
                                <span>{item.pings}</span>
                            </div>
                        </div>
                    </div>
                </Card>
                }

                {
                    visible &&<ImageViewer.Multi
                    images={imgList}
                    visible={visible}
                    defaultIndex={index} 
                    onClose={() => {
                        setVisible(false)
                    }}
                />
                }
                  {
                    commentList.length > 0 &&<div className="clist" style={{marginTop:20 , height:'40vh',overflow:'auto'}}>
                    <List header='面试评论'>
                        {commentList.map((val:any,index:any) => (
                            <List.Item
                                key={val._id}
                                extra={dayjs(val.time).format('MM-DD HH:mm')}
                                prefix={
                                    <Image
                                        src={val.userInfo.avatar?.replace(/public/,base)}
                                        style={{ borderRadius: 20 }}
                                        fit='cover'
                                        width={40}
                                        height={40}
                                    />
                                }
                                description={
                                    <div style={{...styles.center,flexDirection:'column',justifyContent:'flex-start',alignItems:"flex-start"}}>
                                        <div style={{marginTop:5}}>
                                            {val.comment}
                                        </div>
                                        <div style={{marginTop:5}}>
                                            <Rate style={{'--star-size':'16px'}} defaultValue={val.rate} ></Rate>
                                        </div>
                                    </div>
                                }
                            >
                                <span style={{fontSize:12}}>
                                    {val.userInfo.username}{val.userInfo.phone==item!.author?.phone&&<Tag color='danger'>作者</Tag>}
                                </span>
                            </List.Item>
                        ))}
                    </List>
                </div>
                }
            </div>
            <Popup
                visible={show}
                onClose={() => {
                    setShow(false)
                }}
                showCloseButton
                bodyStyle={{
                    borderTopLeftRadius: '8px',
                    borderTopRightRadius: '8px',
                    minHeight: '90vh',
                }}
            >
                <div style={{marginTop:50,padding:10}}>
                    <TextArea
                        className='mt10'
                        style={{border:'1px solid #ddd',borderRadius:10,padding:5}}
                        placeholder='请输入'
                        showCount
                        maxLength={400}
                        rows={6}
                        value={comment}
                        onChange={setComment}
                    />
                    <div style={{...styles.center,color:"#000"}}  className='mt10'>
                        打分:<Rate allowHalf value={rate} onChange={setRate}  />
                    </div>
                    <Button color="primary" block className='mt10' disabled={!comment}  onClick={addToPings} >添加评论</Button>
                </div>
            </Popup>
        </div>

    )
}

export default Datail